<template>
  <div class="excel-to-json app-container">
    <ContentLayout :title="'Excel转Json'">
      <div>
        <UploadExcel v-model:file-list="fileList"></UploadExcel>
        <el-button type="primary" @click="handleToJson">转为json</el-button>
        <el-button type="primary" @click="downloadToJson">下载json</el-button>
        <el-button type="danger" @click="clearJson"> 清空</el-button>
      </div>
    </ContentLayout>
    <SupplementLayout>
      <div class="show-json">
        <div class="default-json">
          <el-input
            v-model="defaultJson"
            type="textarea"
            readonly
            placeholder="默认 JSON 数据"
            class="default-json-input"
            resize="none"
          ></el-input>
        </div>
        <el-button @click="handleFormatJson"> 格式化</el-button>
        <div class="format-json">
          <pre>{{ formatJson }}</pre>
        </div>
      </div>
    </SupplementLayout>
  </div>
</template>

<script setup lang="ts">
import type { UploadUserFile } from "element-plus";
import { ElMessageBox } from "element-plus";
import { ref } from "vue";
import { excelToJson, downloadJson } from "@/utils/excelToJson";
const fileList = ref<UploadUserFile[]>([]);
const defaultJson = ref<string>("");
const formatJson = ref<string>("");
const handleToJson = () => {
  if (fileList.value[0].raw) {
    defaultJson.value = "";
    formatJson.value = "";
    excelToJson(fileList.value[0].raw, true)
      .then((json) => {
        // console.log("转换后的 JSON 数据:", json);
        defaultJson.value = JSON.stringify(json);
        ElMessage.success("excel转换为json成功");

        //   // 是否下载json文件
      })
      .catch((error) => {
        console.error("转换失败:", error);
      });
  }
};
const downloadToJson = () => {
  ElMessageBox.confirm("excel转换为json成功，是否下载文件?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "success",
  })
    .then(() => {
      // 下载json文件
      downloadJson(defaultJson.value, "excelToJson.json");
    })
    .catch(() => {});
};
const clearJson = () => {
  ElMessage.success("清空成功");
  defaultJson.value = "";
  formatJson.value = "";
};
const handleFormatJson = () => {
  // <pre>标签保留文件格式
  if (defaultJson.value) {
    try {
      const json = JSON.parse(defaultJson.value); // 将字符串解析为 JSON 对象
      formatJson.value = JSON.stringify(json, null, 2); // 格式化 JSON，缩进 2 个空格
    } catch (error) {
      console.error("格式化失败:", error);
    }
  }
};
</script>

<style lang="scss" scoped>
.excel-to-json {
  .show-json {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .format-json {
    border: 1px solid $color_1;
  }
  .default-json,
  .format-json {
    overflow-y: auto;
    font-size: 14px;
    width: 45%;
    height: 100%;

    .default-json-input {
      height: 100%;
      width: 100%;
      ::v-deep {
        .el-textarea__inner {
          height: 100%;
          width: 100%;
        }
      }
    }
  }
}
</style>
